package com.paobuji.aidebao.myapplication.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.paobuji.aidebao.myapplication.R;


/**
 * Created by lenovo on 2017/3/16.
 */

public class RectSeekBar extends View {
    private Context mContext = null;

    //指示器的样式 以及大小
    private Drawable mThumbDrawable = null;
    private int mThumbHeight = 0;
    private int mThumbWidth = 0;
    private int[] mThumbNormal = null;
    private int[] mThumbPressed = null;


    //seekBar的最大值
    private int mSeekBarMax = 0;

    //环形圆弧的背景画笔
    private Paint mSeekBarBackgroundPaint = null;
    //环形圆弧的刻度画笔
    private Paint mSeekbarProgressPaint = null;
    private RectF mArcRectF = null;
    //两侧小圆球的画笔
    private Paint mCirclePain = null;


    private boolean mIsShowProgressText = false;//是否显示文字
    private Paint mProgressTextPaint = null; //文字的画笔
    private int mProgressTextSize = 0; //文字的大小

    private int mViewHeight = 0;
    private int mViewWidth = 0;
    private int mSeekBarSize = 0; //seekbar的大小
    private int mSeekBarRadius = 0;//seekbar的弧度
    private int mSeekBarCenterX = 0;
    private int mSeekBarCenterY = 0;

    private float mThumbLeft = 0;
    private float mThumbTop = 0;

    private float mSeekBarDegree = 180;
    private int mCurrentProgress = 0;

    public void setmSeekBarMax(int mSeekBarMax) {
        this.mSeekBarMax = mSeekBarMax;
        mCurrentProgress = (int) (mSeekBarMax * (mSeekBarDegree - 180) / 180);
        invalidate();

    }

    private OnSeekBarChangeListener mOnSeekBarChangeListener = null;

    public void setmOnSeekBarChangeListener(OnSeekBarChangeListener mOnSeekBarChangeListener) {
        this.mOnSeekBarChangeListener = mOnSeekBarChangeListener;
    }

    public interface OnSeekBarChangeListener {

        void onProgressChanged(int progress);

        void onStartTrackingTouch();

        void onStopTrackingTouch();
    }

    public RectSeekBar(Context context) {
        this(context,null);
//        mContext = context;
        //initViewDefault();
//        mArcRectF = new RectF();
    }

    public RectSeekBar(Context context, AttributeSet attrs) {
        this(context,attrs,0);
//        mContext = context;
//        initViewAttrs(attrs);
//        mArcRectF = new RectF();
    }

    public RectSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        mArcRectF = new RectF();
        initViewAttrs(attrs);

    }

    private void initViewAttrs(AttributeSet attrs) {

        TypedArray localTypedArray = mContext.obtainStyledAttributes(attrs, R.styleable.CircleSeekBar);

        //thumb的属性是使用android:thumb属性进行设置的
        //返回的Drawable为一个StateListDrawable类型，即可以实现选中效果的drawable list
        //mThumbNormal和mThumbPressed则是用于设置不同状态的效果，当点击thumb时设置mThumbPressed，否则设置mThumbNormal
        mThumbDrawable = localTypedArray.getDrawable(R.styleable.CircleSeekBar_android_thumb);
        mThumbWidth = mThumbDrawable.getIntrinsicWidth();
        mThumbHeight = mThumbDrawable.getIntrinsicHeight();

        mThumbNormal = new int[]{-android.R.attr.state_focused, -android.R.attr.state_pressed,
                -android.R.attr.state_selected, -android.R.attr.state_checked};
        mThumbPressed = new int[]{android.R.attr.state_focused, android.R.attr.state_pressed,
                android.R.attr.state_selected, android.R.attr.state_checked};

        //seekBar的线的宽度以及颜色
        float progressWidth = localTypedArray.getDimension(R.styleable.CircleSeekBar_progress_width, 5);
        int progressBackgroundColor = localTypedArray.getColor(R.styleable.CircleSeekBar_progress_background, Color.GRAY);
        int progressFrontColor = localTypedArray.getColor(R.styleable.CircleSeekBar_progress_front, Color.BLUE);
        mSeekBarMax = localTypedArray.getInteger(R.styleable.CircleSeekBar_progress_max, 100);

        mSeekbarProgressPaint = new Paint();
        mSeekBarBackgroundPaint = new Paint();

        mSeekbarProgressPaint.setColor(progressFrontColor);
        mSeekBarBackgroundPaint.setColor(progressBackgroundColor);

        mSeekbarProgressPaint.setAntiAlias(true);
        mSeekBarBackgroundPaint.setAntiAlias(true);

        mSeekbarProgressPaint.setStyle(Paint.Style.STROKE);
        mSeekBarBackgroundPaint.setStyle(Paint.Style.STROKE);

        mSeekbarProgressPaint.setStrokeWidth(progressWidth);
        mSeekBarBackgroundPaint.setStrokeWidth(progressWidth);
        /**
         * 初始化两侧的画笔
         */
        mCirclePain = new Paint();
        mCirclePain.setColor(getResources().getColor(R.color.colorBall));
        mCirclePain.setAntiAlias(true);
        mCirclePain.setStyle(Paint.Style.FILL);
        mCirclePain.setStrokeWidth(progressWidth);

        /**
         * 显示的字
         */

        mIsShowProgressText = localTypedArray.getBoolean(R.styleable.CircleSeekBar_show_progress_text, false);
        int progressTextStroke = (int) localTypedArray.getDimension(R.styleable.CircleSeekBar_progress_text_stroke_width, 5);
        int progressTextColor = localTypedArray.getColor(R.styleable.CircleSeekBar_progress_text_color, Color.GREEN);
        mProgressTextSize = (int) localTypedArray.getDimension(R.styleable.CircleSeekBar_progress_text_size, 50);

        mProgressTextPaint = new Paint();
        mProgressTextPaint.setColor(progressTextColor);
        mProgressTextPaint.setAntiAlias(true);
        mProgressTextPaint.setStrokeWidth(progressTextStroke);
        mProgressTextPaint.setTextSize(mProgressTextSize);

        localTypedArray.recycle();
    }


    @Override
    protected  void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        mViewWidth = getWidth();//获得seekBar的宽度
        mViewHeight = getHeight();//获得seekbar的高度

        if (mViewHeight < 2 * mViewWidth) {
            mSeekBarSize = mViewHeight; //根据高度来设置半径
        } else {
            mSeekBarSize = mViewWidth / 2;
        }


        //获得该view范围内的中心点
        mSeekBarCenterX = mViewWidth / 2;
        mSeekBarCenterY = 9 * mViewHeight / 10;
        //圆弧的半径
        mSeekBarRadius = 9 * mSeekBarSize / 10 - mThumbWidth / 2;

        //在view的绘制范围
        int left = mSeekBarCenterX - mSeekBarRadius;
        int right = mSeekBarCenterX + mSeekBarRadius;
        int top = mSeekBarCenterY - mSeekBarRadius;
        int bottom = mSeekBarCenterY + mSeekBarRadius;
        mArcRectF.set(left, top, right, bottom);

        // 起始位置，三点钟方向
        setThumbPosition(Math.toRadians(mSeekBarDegree));
    }

    @Override
    protected  void onDraw(Canvas canvas) {
        canvas.drawArc(this.mArcRectF, 180, 180, false, mSeekBarBackgroundPaint);
        canvas.drawArc(this.mArcRectF, 180, mSeekBarDegree - 180, false, mSeekbarProgressPaint);

        canvas.drawCircle(mSeekBarCenterX - mSeekBarRadius, mSeekBarCenterY, 30f, mCirclePain);
        canvas.drawCircle(mSeekBarCenterX + mSeekBarRadius, mSeekBarCenterY, 30f, mCirclePain);

        drawThumbBitmap(canvas);
        drawProgressText(canvas);

        super.onDraw(canvas);
    }

    //绘制seekBar的拖动
    private void drawThumbBitmap(Canvas canvas) {
        if (null != mThumbDrawable) {
            mThumbDrawable.setBounds((int) mThumbLeft, (int) mThumbTop,
                    (int) (mThumbLeft + mThumbWidth), (int) (mThumbTop + mThumbHeight));
            mThumbDrawable.draw(canvas);
        }
    }

    private float oldmax;
    private boolean isFrist = true;

    //绘制文字
    private void drawProgressText(Canvas canvas) {
        if (true == mIsShowProgressText) {
            float textWidth = mProgressTextPaint.measureText(mCurrentProgress + mContext.getString(R.string.unit));
            canvas.drawText(mCurrentProgress + mContext.getString(R.string.unit), mSeekBarCenterX - textWidth / 2, mSeekBarCenterY
                    + mProgressTextSize / 2, mProgressTextPaint);

        }
    }

    private void setThumbPosition(double radian) {
        double x = mSeekBarCenterX + mSeekBarRadius * Math.cos(radian);
        double y = mSeekBarCenterY + mSeekBarRadius * Math.sin(radian);
        mThumbLeft = (float) (x - mThumbWidth / 2);
        mThumbTop = (float) (y - mThumbHeight / 2);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float eventX = event.getX();
        float eventY = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (null != mOnSeekBarChangeListener) {
                    mOnSeekBarChangeListener.onStartTrackingTouch();
                }
                seekTo(eventX, eventY, false);
                break;

            case MotionEvent.ACTION_MOVE:
                seekTo(eventX, eventY, false);
                break;

            case MotionEvent.ACTION_UP:
                if (null != mOnSeekBarChangeListener) {
                    mOnSeekBarChangeListener.onStopTrackingTouch();
                }
                seekTo(eventX, eventY, true);
                break;
        }
        return true;
    }

    private void seekTo(float eventX, float eventY, boolean isUp) {
        if (true == isPointOnThumb(eventX, eventY) && false == isUp) {
            if (null != mThumbDrawable) {
                mThumbDrawable.setState(mThumbPressed);
            }
            double radian = Math.atan2(eventY - mSeekBarCenterY, eventX - mSeekBarCenterX);
            /*
             * 由于atan2返回的值为[-pi,pi]
             * 因此需要将弧度值转换一下，使得区间为[0,2*pi]
             */
            if (radian < 0) {
                radian = radian + 2 * Math.PI;
            }
            setThumbPosition(radian);

            mSeekBarDegree = (float) Math.round(Math.toDegrees(radian));
            mCurrentProgress = (int) (mSeekBarMax * (mSeekBarDegree - 180) / 180);
            if (null != mOnSeekBarChangeListener) {
                mOnSeekBarChangeListener.onProgressChanged(mCurrentProgress);
            }
            invalidate();
        } else {
            if (null != mThumbDrawable) {
                mThumbDrawable.setState(mThumbNormal);
            }
            invalidate();
        }
    }

    //判断是否在圆弧上
    private boolean isPointOnThumb(float eventX, float eventY) {
        boolean result = false;
        double distance = Math.sqrt(Math.pow(eventX - mSeekBarCenterX, 2)
                + Math.pow(eventY - mSeekBarCenterY, 2));
        if (distance < mSeekBarSize && distance > (mSeekBarSize / 2 - mThumbWidth)) {
            result = true;
        }
        if (eventY - mSeekBarCenterY > 0) {
            result = false;
        }
        return result;
    }

    public int getmCurrentProgress() {
        return mCurrentProgress;
    }

    public void setmCurrentProgress(int mCurrentProgress) {
        this.mCurrentProgress = mCurrentProgress;
        //mCurrentProgress = (int) (mSeekBarMax * (mSeekBarDegree-180) / 180);
        mSeekBarDegree = 180 * mCurrentProgress / mSeekBarMax + 180;
        invalidate();
    }

}
